package ua.com.minus1.lookbattle;

import android.app.Activity;
import android.content.Context;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.util.Log;
import android.util.SparseBooleanArray;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.*;
import com.actionbarsherlock.app.SherlockListFragment;
import com.actionbarsherlock.view.ActionMode;
import com.actionbarsherlock.view.Menu;
import com.actionbarsherlock.view.MenuItem;
import ua.com.minus1.lookbattle.models.CacheFolder;
import ua.com.minus1.lookbattle.models.Look;
import ua.com.minus1.lookbattle.models.LooksResult;
import ua.com.minus1.lookbattle.net.HttpManager;
import ua.com.minus1.lookbattle.net.ImageManager;
import ua.com.minus1.lookbattle.net.URLManager;
import ua.com.minus1.lookbattle.utils.AppPreferences;
import ua.com.minus1.lookbattle.utils.BundleValues;

import java.util.List;

/**
 * Created with IntelliJ IDEA.
 * User: Flash
 * Date: 26.09.12
 * Time: 11:26
 * To change this template use File | Settings | File Templates.
 */
public class LooksListFragment extends SherlockListFragment {

    private HttpManager mHttpManager;
    private AppPreferences mPreferences;
    private int mCatId;
    private int lookId;

    private Callbacks mCallbacks;
    ImageManager mImageManager;
    LooksAdapter mAdapter;
    LooksResult mLooksResult;
    private ActionMode mActionMode;

    public void update() {
        loadLooks();
    }

    public void refresh() {
        mHttpManager.clearCache();
        loadLooks();
    }

    public interface Callbacks{
        void onLookSelected(int lookId, int position);
    }

    public static LooksListFragment newInstance(int catId) {
        LooksListFragment f = new LooksListFragment();

        Bundle args = new Bundle();
        args.putInt(BundleValues.CAT_ID, catId);
        f.setArguments(args);

        return f;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setHasOptionsMenu(true);
    }

    @Override
    public void onViewCreated(View view, Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        setEmptyText("No looks in this category yet.");
        ListView listView = getListView();
        listView.setOnItemLongClickListener(new ListItemLongClickListener());
        //listView.setOnItemLongClickListener(new ListOnLongClickListener());
    }

    @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);
        if (!(activity instanceof Callbacks)) {
            throw new ClassCastException("Activity must implement fragment's callbacks.");
        }

        mCallbacks = (Callbacks) activity;
    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);

        mHttpManager = new HttpManager(getActivity(), CacheFolder.HTTP_MY_LOOKS);
        mImageManager = new ImageManager(getActivity(), CacheFolder.IMAGES_MY_LOOKS);
        mPreferences = new AppPreferences(getActivity());

        mCatId = getArguments().getInt(BundleValues.CAT_ID, 0);
        Log.i(LooksListFragment.class.getName(), "cat id is " + String.valueOf(mCatId));

        if(savedInstanceState == null)
            mHttpManager.clearCache();

        loadLooks();
    }

    private void loadLooks() {
        mHttpManager.loadClass(URLManager.getMyLooksURL(mPreferences.getUUID(), mCatId), LooksResult.class, new HttpManager.HttpResultHandler<LooksResult>() {
            public void onResultLoadComplete(LooksResult result) {
                mLooksResult = result;
                //progress.setVisibility(View.GONE);
                if (mLooksResult != null) {
                    Log.i(LooksListFragment.class.getName(), "Looks request result " + mLooksResult);
                    List<Look> looks = mLooksResult.looks;
                    mAdapter = new LooksAdapter(getActivity(), looks);
                    setListAdapter(mAdapter);
                } else {
                    setListAdapter(null);
                    //emptyText.setVisibility(View.VISIBLE);
                    //Log.i(MyLooksActivity.class.getName(), "Looks request result is null");
                }

            }
        }, HttpManager.USE_CACHE);
    }

    public int[] getItemsIds() {
        int[] ids = new int[mLooksResult.looks.size()];
        for (int i = 0; i < ids.length; i++) {
            ids[i] = mLooksResult.looks.get(i).lookId;
        }
        return ids;
    }



    @Override
    public void onListItemClick(ListView l, View v, int position, long id) {
        if (mActionMode == null) {
            if(getListView().getChoiceMode() != ListView.CHOICE_MODE_NONE)
                getListView().setChoiceMode(ListView.CHOICE_MODE_NONE);
            lookId = mAdapter.getItem(position).lookId;
            mCallbacks.onLookSelected(lookId, position);
        } else {
            onListItemCheck(position);
        }
    }

    private void onListItemCheck(int position) {
        //getListView().se
        SparseBooleanArray checkedItems = getListView().getCheckedItemPositions();
        //getListView().setItemChecked(position, checkedItems.valueAt(position));
        boolean hasCheckedItems = false;
        for (int i = 0; i < checkedItems.size() && !hasCheckedItems; i++) {
            hasCheckedItems = checkedItems.valueAt(i);
        }

        if(hasCheckedItems && mActionMode == null)
            mActionMode = getSherlockActivity().startActionMode(new MyActionModeCallback());
        else if(!hasCheckedItems && mActionMode != null)
            mActionMode.finish();
    }

    private void deleteSelectedItems() {
        Log.d(LooksListFragment.class.getName(), "delete selected items: " + getListView().getCheckedItemPositions().toString());
    }

    private class ListItemLongClickListener implements AdapterView.OnItemLongClickListener {
        public boolean onItemLongClick(AdapterView<?> adapterView, View view, int i, long l) {
            getListView().setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
            getListView().setItemChecked(i, true);
            onListItemCheck(i);
            return true;
        }
    }

    private class LooksAdapter extends ArrayAdapter<Look> {
        private LooksAdapter(Context context, List<Look> looks) {
            super(context, R.layout.list_item_look, looks);
        }

        public void updateItemBonuses(int position, View convertView, int bonuses) {
            getItem(position).bonuses = bonuses;
            ViewHolder viewHolder = (ViewHolder) convertView.getTag();
            viewHolder.bonuses.setText(String.valueOf(bonuses));
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            final ViewHolder viewHolder;

            final Look lookItem = getItem(position);

            if (convertView == null) {
                LayoutInflater inflater = (LayoutInflater) getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
                convertView = inflater.inflate(R.layout.list_item_look, null);

                viewHolder = new ViewHolder();
                viewHolder.image = (ImageView) convertView.findViewById(R.id.lookItemImage);
                viewHolder.progress = convertView.findViewById(R.id.lookItemProgress);
                viewHolder.battles = (TextView) convertView.findViewById(R.id.lookRatesBattles);
                viewHolder.awards = (TextView) convertView.findViewById(R.id.lookRatesLocalPace);
                viewHolder.winnings = (TextView) convertView.findViewById(R.id.lookRatesWinnings);
                viewHolder.bonuses = (TextView) convertView.findViewById(R.id.lookRatesBonuses);

                convertView.setTag(viewHolder);
            } else
                viewHolder = (ViewHolder) convertView.getTag();

            viewHolder.position = position;
            viewHolder.image.setImageBitmap(null);
            viewHolder.progress.setVisibility(View.VISIBLE);
            viewHolder.battles.setText(String.valueOf(lookItem.battles));
            viewHolder.awards.setText(String.valueOf(lookItem.awards));
            viewHolder.winnings.setText(String.valueOf(lookItem.winnings));
            viewHolder.bonuses.setText(String.valueOf(lookItem.bonuses));
//            Log.i(MyLooksActivity.class.getName(), lookItem.image);

            mImageManager.loadBitmap(lookItem.image, viewHolder.image, new ImageManager.BitmapLoadListener() {
                public void onLoadComplete(Bitmap bitmap) {
                    viewHolder.progress.setVisibility(View.GONE);
                    //Log.i(MyLooksActivity.class.getName(), "image loaded");
                }
            }, ImageManager.USE_CACHE);

            return convertView;
        }

        private class ViewHolder {
            public int position;
            public ImageView image;
            public View progress;
            public TextView battles;
            public TextView awards;
            public TextView bonuses;
            public Button convertBtn;
            public TextView winnings;
        }
    }

    private class MyActionModeCallback implements ActionMode.Callback{
        public boolean onCreateActionMode(ActionMode actionMode, Menu menu) {
            actionMode.getMenuInflater().inflate(R.menu.looks_action, menu);
            return true;
        }

        public boolean onPrepareActionMode(ActionMode actionMode, Menu menu) {
            return false;  //To change body of implemented methods use File | Settings | File Templates.
        }

        public boolean onActionItemClicked(ActionMode actionMode, MenuItem menuItem) {
            deleteSelectedItems();
            actionMode.finish();
            return true;
        }

        public void onDestroyActionMode(ActionMode actionMode) {
            ListView mListView = getListView();
            SparseBooleanArray checkedItems = mListView.getCheckedItemPositions();

            for (int i = 0; i < checkedItems.size(); i++) {
                if(checkedItems.get(i))
                    mListView.setItemChecked(i, false);
            }
//            final ListView mListView = getListView();
//            for (int i = 0; i < getListAdapter().getCount(); i++) {
//                 mListView.setItemChecked(i, false);
//            }
            //((LooksAdapter) getListAdapter()).notifyDataSetChanged();
           /* mListView.addOnLayoutChangeListener(new View.OnLayoutChangeListener() {
                public void onLayoutChange(View view, int i, int i2, int i3, int i4, int i5, int i6, int i7, int i8) {
                    mListView.setChoiceMode(ListView.CHOICE_MODE_NONE);
                    //mListView.removeOnLayoutChangeListener(this);
                }
            });*/


            if(actionMode == mActionMode)
                mActionMode = null;


        }

    }


}
